#!/usr/bin/env node

const program = require('commander')
const {resolve} = require('path')
const fs = require('fs')
const pwd = process.cwd()
const isDir = path => fs.statSync(path).isDirectory()
const isFile = path => fs.statSync(path).isFile()
const isExist = path => fs.existsSync(path)
program
    .version('1.2.0')
    .allowUnknownOption()
    .option('-t, --type [filetype...]',"filetype to count",['js'])
    .option('-d, --directory [dir...]',"the directory or file to count",['.'])
    .option('-n, --no-modules [bol]', "if node_modules count in",true)

program.parse(process.argv)

const opts = program.opts()
if(typeof opts.modules !== 'boolean'){
    if(opts.modules === 'false'){
        opts.modules = false
    }else if(opts.modules === 'true'){
        opts.modules = true
    }else {
        console.log("option -n only apply true/false")
        process.exit(0)
    }
}
let total = count(opts.directory)
console.log(total)

function count(dir_list){
    let total = 0
    for(let dir of dir_list){
        if(!isExist(resolve(pwd,dir))){
            console.log(`no such file ${dir}`)
            process.exit(0)
        }
        if(isDir(dir)){
            total += countLineOfDir(resolve(pwd,dir))
        }else if(isFile(dir)){
            total += countLineOfFile(resolve(pwd,dir))
        }
    }
    return total
}

function countLineOfDir(path){
    let total = 0
    if(opts.modules){
        if(path.indexOf('node_modules') > -1){
            return 0
        }
    }
    let f_list = fs.readdirSync(path)
    for(let item of f_list){
        let newPath = resolve(path,item)
        if(isDir(newPath)){
            total += countLineOfDir(newPath)
        }else if(isFile(newPath)){
            total += countLineOfFile(newPath)
        }
    }
    return total
}

function countLineOfFile(path){
    let total = 1
    if(!isTypeInTypeList(path,opts.type)){
        return 0
    }
    let f = fs.readFileSync(path)
    for(let cap of f.toString()){
        if(cap === '\n'){
            total += 1
        }
    }
    return total
}

function isTypeInTypeList(type,type_list){
    return type_list.some(item => {
        return type.slice(type.lastIndexOf('.') + 1) === item
    })
}